/****************************************************
          File Name:stack.h
          Author: Abby Cin
          Mail: abbytsing@gmail.com
          Created Time: Sun 08 Feb 2015 08:36:27 PM CST
*****************************************************/

#ifndef stack_h_
#define stack_h_

#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>

typedef struct STACK
{
    char data[10];
    int count;
    struct STACK *next;
} Stack;

int MAX;    // Stack max

bool InitStack(Stack **s)
{
    *s = (Stack *)malloc(sizeof(Stack));
    if(!s) return false;
    (*s)->data[0] = '\0';
    (*s)->next = NULL;
    return true;
}

void DestroyStack(Stack *s)
{
    Stack *tmp, *cur;

    cur = s;
    while(cur != NULL)
    {
        tmp = cur->next;
        printf("free: %s\n", (cur->data[0]=='\0' ? "head" : cur->data));
        free(cur);
        cur = tmp;
    }
}

bool isEmpty(Stack *s)
{
    return s->count == 0 ? true : false;
} 

bool isFull(Stack *s)
{
    return s->count == MAX ? true : false;
}

bool GetTop(Stack *s, char *element)
{
    if(s->count == 0) return false;

    for(int i=0; s->next->data[i] != '\0'; i++)
        element[i] = s->next->data[i];
    return true;
}

bool Push(Stack **s, char *element)
{
    if(isFull(*s)) return false;
    Stack *cur;

    cur = (Stack *)malloc(sizeof(Stack));
    for(int i=0; element[i] != 0; i++)
        cur->data[i] = element[i];
    cur->next = (*s)->next;
    (*s)->next = cur;
    (*s)->count++;
    return true;
}

bool Pop(Stack **s, char *element)
{
    if((*s)->count == 0) return false;
    Stack *cur, *tmp;

    cur = (*s)->next;      // the top element
    for(int i=0; cur->data[i] != '\0'; i++)
        element[i] = cur->data[i];

    tmp = cur->next; // the second element
    (*s)->next = tmp;      // after this, tmp is the top element
    (*s)->count--;
    free(cur);      // free top element
    return true;
}

int StackLength(Stack *s)
{
    return s->count;
}

#endif
